<template>
	<el-upload
		class="avatar-uploader"
		:action="state.uploadUrl"
		:data="state.data"
		:show-file-list="false"
		:on-success="handleAvatarSuccess"
		:before-upload="beforeAvatarUpload"
		accept="image/png, image/jpeg"
	>
		<img v-if="state.imageUrl || props.imageUrl" :src="state.imageUrl || props.imageUrl" class="avatar" />
		<el-icon v-else class="avatar-uploader-icon">
			<elementPlus />
		</el-icon>
	</el-upload>
</template>

<script lang="ts" setup>
import {onMounted, reactive, defineEmits} from 'vue';
import { getOssToken } from '/@/api/common';
import { randomString } from '/@/utils/other';
import { UploadFile } from 'element-plus/es/components/upload/src/upload.type';

const emit = defineEmits(['setImageUrl']);

// eslint-disable-next-line no-undef
const props = defineProps(['imageUrl']);

const state = reactive({
	imageUrl: '',
	uploadUrl: '',
	data: {
		token: '',
		key: '',
	},
	callbackUrl: '',
});

/**
 * 上传成功
 */
const handleAvatarSuccess = (res: any) => {
	let imageURL = state.callbackUrl + res.key;
	state.imageUrl = imageURL;
	emit('setImageUrl', imageURL);
};

/**
 * 上传代码之前
 */
const beforeAvatarUpload = (file: UploadFile) => {
	let suffix = file.name.substring(file.name.lastIndexOf('\.') + 1);
	state.data.key = randomString(10) + new Date().getTime() + '.' + suffix;
};

onMounted(() => {
	getOssToken().then((res: any) => {
		state.uploadUrl = res.data.uploadUrl;
		state.data.token = res.data.accessToken;
		state.callbackUrl = res.data.callbackUrl;
	});
});
</script>

<style scoped>
.avatar-uploader {
	border: 1px dashed #d9d9d9;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
	width: 150px;
	height: 150px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.avatar-uploader {
	border-color: #409eff;
}

.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	position: relative;
}

.avatar-uploader-icon::before {
	content: '';
	position: absolute;
	top: -56px;
	left: -60px;
	width: 150px;
	height: 150px;
}

.avatar {
	width: 100%;
	height: 100%;
	display: block;
}
</style>
